﻿using Cc.Util;
using Magic.Core;
using Magic.Core.Entity;
using Magic.Core.Service;
using ManagementTools.Model;
using ManagementTools.Service.Dto;
using ManagementTools.Util;
using Mapster;
using MiniExcelLibs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace ManagementTools.Forms
{
    public partial class FrmOrgUserInporter : Form
    {
        
        private List<string> mSheetNames;
        private List<OrgXto> mOrgs;
        private List<RoleXto> mRoles;
        private List<PosXto> mPoses;
        private List<UserXto> mUsers;
        private List<EmpXto> mEmps;
        private List<UserRoleXto> mUserRoles;
        private List<EmpPosXto> mEmpPoses;
        private List<EmpExtOrgPosXto> mEmpExtOrgPoses;
        private List<RoleOrgXto> mRoleOrgs;

        public FrmOrgUserInporter()
        {
            InitializeComponent();
        }

        private void FrmOrgUserInporter_Load(object sender, EventArgs e)
        {
            dgvOrgs.AutoGenerateColumns = false;
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog()
            {
                Title = "打开数据文件",
                Filter = "Excel 文件(*.xlsx)|*.xlsx|全部文件(*.*)|*.*",
                RestoreDirectory = true,
                Multiselect = false
            };
            if (fd.ShowDialog() == DialogResult.OK)
            {
                
                mSheetNames = MiniExcel.GetSheetNames(fd.FileName);
                if (!mSheetNames.Contains("机构")&&mSheetNames.Count!=7)
                {
                    MessageBox.Show("指定的文件不是用户初始化文件", "错误：文件非法", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                //从excel读入角色数据
                mRoles = MiniExcel.Query<RoleXto>(fd.FileName, sheetName: "角色").ToList();
                dgvRoles.DataSource = null;
                dgvRoles.DataSource = mRoles;
                //从excel读入用户数据
                mUsers = MiniExcel.Query<UserXto>(fd.FileName, sheetName: "用户").ToList();
                dgvUsers.DataSource = null;
                dgvUsers.DataSource = mUsers;
                //从excel读入用户-角色数据
                mUserRoles = MiniExcel.Query<UserRoleXto>(fd.FileName, sheetName: "用户角色").ToList();
                dgvUserRole.DataSource = null;
                dgvUserRole.DataSource = mUserRoles;

                //从excel读入机构数据
                mOrgs = MiniExcel.Query<OrgXto>(fd.FileName, sheetName: "机构").ToList();
                dgvOrgs.DataSource = null;
                dgvOrgs.DataSource = mOrgs;
                //从excel读入职位数据
                mPoses = MiniExcel.Query<PosXto>(fd.FileName, sheetName: "职位").ToList();
                dgvPoses.DataSource = null;
                dgvPoses.DataSource = mPoses;

                //从excel读入员工表
                mEmps = MiniExcel.Query<EmpXto>(fd.FileName, sheetName: "员工表").ToList();
                dgvEmp.DataSource = null;
                dgvEmp.DataSource = mEmps;
               
                //从excel读入用户-职位数据
                mEmpPoses = MiniExcel.Query<EmpPosXto>(fd.FileName, sheetName: "员工职位").ToList();
                dgvEmpPos.DataSource = null;
                dgvEmpPos.DataSource = mEmpPoses;

                //从excel读入员工附加机构和职位
                mEmpExtOrgPoses = MiniExcel.Query<EmpExtOrgPosXto>(fd.FileName, sheetName: "员工其他机构和职位").ToList();
                dgvEmpExtOrgPos.DataSource = null;
                dgvEmpExtOrgPos.DataSource = mEmpExtOrgPoses;

                //从excel读入角色权限表
                mRoleOrgs = MiniExcel.Query<RoleOrgXto>(fd.FileName, sheetName: "角色数据范围").ToList();
                dgvEmpExtOrgPos.DataSource = null;
                dgvEmpExtOrgPos.DataSource = mEmpExtOrgPoses;
            }
        }
       
        

        private void btnSumit_Click(object sender, EventArgs e)
        {

            int count = 0;            
            //提交机构信息
            foreach (var org in mOrgs)
            {
                var ans = MagicHelper.ExistOrg(org.Name);
                if (ans == null)
                {
                    MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;

                }
                else if (ans == false)
                {
                    var entity = org.Adapt<OrgInput>();
                    var pid = GetParentId(org);
                    entity.Pid = pid;
                    if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysOrg/add", RequestType.Post, App.Token, out string respData, entity))
                    {
                        MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    count++;
                }
            }
            AppendEcho(0, $"新增{count}个机构");
            //保存职位信息
            count = 0;
            foreach (var pos in mPoses)
            {
                var ans = MagicHelper.ExistPos(pos.Name);
                if (ans == null)
                {
                    MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;

                }
                else if (ans == false)
                {
                    var entity = pos.Adapt<PosInput>();
                    if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysPos/add", RequestType.Post, App.Token, out string respData, entity))
                    {
                        MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    count++;
                }
            }
            AppendEcho(0, $"新增{count}个职位");

            //保存用户 用户通过SysEmp共用ID实现用户和员工的关联，所以应该先存入组织架构,拿到组织Id再存入用户 
            count = 0;
            foreach (var user in mUsers.Where(u => u.Name != "系统管理员"))
            {
                var ans = MagicHelper.ExistUser(user.Name);
                if (ans == null)
                {
                    MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else if (ans == false) //用户不存在，新增
                {
                    long orgId = 0;
                    var userInput = user.Adapt<AddUserInput>();
                    userInput.Confirm = user.Password;
                    //有则加入组织架构
                    var emp = mEmps.FirstOrDefault(em => em.Name == userInput.Name);
                    if(emp!=null)
                    {
                        var orgs = MagicHelper.FindListByField<OrgOutput>(App.ApiServer + "/sysOrg/Find", emp.OrgName);
                        if (orgs.Any())
                        {
                            var org = orgs.First();
                            userInput.SysEmpParam.JobNum = emp.JobNum;//用户的员工代码
                            userInput.SysEmpParam.OrgName = org.Name;//用户所属机构名
                            userInput.SysEmpParam.OrgId = org.Id;//用户所属机构Id
                            orgId = orgId.ParseToLong();
                        }
                        else
                        {
                            MessageBox.Show($"找不到名为{emp.Name}的用户或者名为{emp.OrgName}的机构", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        //添加职位
                        var xpos = mEmpPoses.FirstOrDefault(p => p.Name == user.Name);
                        if(xpos!=null)
                        {
                            var pos = MagicHelper.FindListByField<SysPos>(App.ApiServer + "/sysPos/Find", xpos.PosName);
                            if(pos!=null&&pos.Any())
                            {
                                userInput.SysEmpParam.PosIdList.Add(pos.First().Id);
                            }
                        }
                        
                    }
                   
                    if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysUser/add", RequestType.Post, App.Token, out string respData, userInput))
                    {
                        MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    //写入用户后，给用户授权所属机构
                    var uusers= MagicHelper.FindListByField<UpdateUserInput>(App.ApiServer + "/sysUser/Find", user.Name);
                    if(uusers!=null&&uusers.Any())
                    {
                        UpdateUserInput updateUser = uusers.First();
                        userInput.GrantOrgIdList.Add(orgId);//给用户授权所述机构的权限
                        if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysUser/grantData", RequestType.Post, App.Token, out respData, updateUser))
                        {
                            MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                   
                    count++;

                }
            }
            AppendEcho(0, $"新增{count}个用户");

            //保存员工其他机构和职位
            count = 0;
            foreach (var eop in mEmpExtOrgPoses)
            {
                var users = MagicHelper.FindListByField<UserOutput>(App.ApiServer + "/sysUser/Find", eop.Name);
                if (users.Any())
                {
                    var user = users.First().Adapt<UpdateUserInput>();//转换为UpdateUserInput
                    var emps = MagicHelper.FindListByField<EmpOutput2>(App.ApiServer + "sysEmp/FindJobnum", user.SysEmpParam.JobNum, "Jobnum");
                    var orgs = MagicHelper.FindListByField<OrgOutput>(App.ApiServer + "/sysOrg/Find", eop.OrgName);
                    var poses = MagicHelper.FindListByField<UserOutput>(App.ApiServer + "/sysPos/Find", eop.PosName);
                    if (emps!=null && orgs.Any() && poses.Any())
                    {
                        SysEmpExtOrgPos ext = new()
                        {
                            SysPosId = poses.First().Id.ParseToLong(),
                            SysEmpId = emps.First().Id.ParseToLong(),
                            SysOrgId = orgs.First().Id.ParseToLong(),
                        };
                        if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysPos/add", RequestType.Post, App.Token, out string respData, ext))
                        {
                            MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        count++;
                    }
                }
                else
                {
                    MessageBox.Show($"找不到名为{eop.Name}的用户", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            AppendEcho(0, $"新增{count}个附加机构和职位");

            //保存角色信息
            count = 0;
           
            foreach (var role in mRoles)
            {
                var ans = MagicHelper.ExistRole(role.Name);
                if (ans == null)
                {
                    MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;

                }
                else if (ans == false)
                {
                    RoleInput entity = role.Adapt<RoleInput>();
                    

                    if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysRole/add", RequestType.Post, App.Token, out string respData, entity))
                    {
                        MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    #region 授权部门数据时总是只能写入一个，暂停执行
                    //给角色授权部门数据
                    //GrantRoleDataInput grant = entity.Adapt<GrantRoleDataInput>();授权部门数据时总是只能写入一个，暂停执行
                    //switch (role.GrantType)
                    //{
                    //    case "全部数据":
                    //        grant.DataScopeType = DataScopeType.ALL;
                    //        break;
                    //    case "授权部门及以下数据":
                    //        grant.DataScopeType = DataScopeType.DEPT_WITH_CHILD;
                    //        break;
                    //    case "授权部门数据":
                    //        grant.DataScopeType = DataScopeType.DEPT;
                    //        break;
                    //    case "仅本人数据":
                    //        grant.DataScopeType = DataScopeType.SELF;
                    //        break;
                    //    case "自定义数据":
                    //        grant.DataScopeType = DataScopeType.DEFINE;
                    //        break;
                    //    default:
                    //        break;
                    //}
                    //foreach (var org in mRoleOrgs.Where(r => r.RoleName == role.Name))
                    //{
                    //    var orgs = MagicHelper.FindListByField<OrgOutput>(App.ApiServer + "/sysOrg/Find", org.OrgName);
                    //    if (orgs.Any())
                    //    {
                    //        grant.GrantOrgIdList.Add(orgs.First().Id.ParseToLong());
                    //    }
                    //}
                    //if (grant.GrantOrgIdList.Count > 0)
                    //{
                    //    if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysRole/grantData", RequestType.Post, App.Token, out respData, grant))
                    //    {
                    //        MessageBox.Show($"授权 时发生错误 角色名：{grant.Name} 授权数据类型: {grant.DataScopeType}  部门数量: {grant.GrantOrgIdList.Count}" +
                    //            $"\r\n" + MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //        return;
                    //    }
                    //    count++;
                    //} 
                    #endregion
                    count++;
                }
               
            }
            AppendEcho(0, $"新增{count}个角色");
            //保存用户角色
            count = 0;
            foreach (var ur in mUserRoles.Where(u => u.Name != "系统管理员"))
            {
                var users = MagicHelper.FindListByField<UserOutput>(App.ApiServer + $"/sysUser/Find", ur.Name);
                var roles = MagicHelper.FindListByField<RoleOutput>(App.ApiServer + $"/sysRole/Find", ur.RoleName);

                if (users.Count > 0 && roles.Count > 0)
                {
                    var user = users.First().Adapt<UpdateUserInput>();
                    user.GrantRoleIdList.Add(roles.First().Id);
                    if (!MagicHelper.ExecuteHttpReturnData(App.ApiServer + "/sysUser/grantRole", RequestType.Post, App.Token, out string respData, user))
                    {
                        MessageBox.Show(MagicHelper.ErrMsg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    count++;
                }
            }
            AppendEcho(0, $"新增{count}条用户角色");


            MessageBox.Show("完美","工作完成",MessageBoxButtons.OK,MessageBoxIcon.Information);
        }
        private void AppendEcho(int level,params string[] lines)
        {
            string space = "".PadRight(level * 2, ' ');

            foreach (var text in lines)
            {
                lstEcho.Items.Add(space + text);
            }
            lstEcho.TopIndex = lstEcho.Items.Count - 5;
            lstEcho.Refresh();
        }
      
        private string GetParentId(OrgXto org)
        {
            //查询父机构ID
            string url = App.ApiServer + "/sysOrg/list";
            if (MagicHelper.ExecuteHttpReturnData<OrgXto, List<OrgOutput>>(url, RequestType.Get, App.Token, out List<OrgOutput> list))
            {
                var orgOut = list.FirstOrDefault(o => o.Name == org.PName);
                return orgOut == null ? "" : orgOut.Id;
            }
            return "";
        }
       

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
